import React, { useEffect, useState, useRef } from 'react'
import { Card, Row, Col, Input, Button, Table, Modal, message,Spin } from 'antd';
import axios from 'axios';
import { useNavigate } from 'react-router-dom';
import { ExclamationCircleOutlined } from '@ant-design/icons';
import request from '../../../utils/request';

export default function User() {
  const { Search } = Input;
  const navigate = useNavigate()
  //文章列表
  const [articleList, setArticleList] = useState([])
  //用户名
  const [title, setTitle] = useState('')
  //分类id数组
  const [CidList, setCidList] = useState([])
  //加载中
  const [loading,setLoading] = useState(true)
  //分类数组
  const [categoryList,setCategoryList] = useState([])

  //分页器配置
  const [paginationOption, setPaginationOption] = useState({
    current: 1,
    defaultCurrent: 1,
    pageSizeOptions: ['2', '4', '6'],
    defaultPageSize: 4,
    total: 0,
    showSizeChanger: true,
    showTotal: (total) => `共${total}篇`,
    onChange: (page, pageSize) => {
      paginationOption.defaultPageSize = pageSize
      paginationOption.current = page
      getArticle()
    },
    onShowSizeChange: (current, size) => {
      paginationOption.defaultCurrent = current
      paginationOption.defaultPageSize = size
      getArticle()
    }
  })
  let titleRef = useRef()
  titleRef.current = title
  let CidRef = useRef
  CidRef.current = CidList[0]

  useEffect(() => {
    getArticle()
  }, [title])

  useEffect(() => {
    getArticle()
    getCategory()
  }, [ CidList])
  //获取文章列表
  function getArticle() {
    setLoading(true)
    axios.get(`/v1/article/artiInfo/cates?`, {
      params: {
        pagesize: paginationOption.defaultPageSize,
        pagenum: paginationOption.current,
        title: titleRef.current,
        cid: CidRef.current
      }
    }).then(
      (res) => {
        console.log(res);
        setArticleList(res.data.data)
        setPaginationOption({ ...paginationOption, total: res.data.total })
        setLoading(false)
      },
      (err) => {
        console.log(err);
      }
    )
  }
  // 搜索文章
  function articleSearch(key) {
    key = key.trim()
    setTitle(() => key)
    setPaginationOption((paginationOption) => ({ ...paginationOption, current: 1 }))
  }
  //添加文章
  const addArticle = (ID = 0) => {
    navigate({ pathname: '/file/write', search: `?id=${ID}` })

  }
  //确定删除文章
  function confirm(ID) {
    Modal.confirm({
      title: '是否确定删除该文章',
      icon: <ExclamationCircleOutlined />,
      content: '一旦删除将不可逆转',
      onOk() { deleteArticle(ID) },
      onCancel() {
        message.info('已取消删除')
      },
      okText: '确认',
      cancelText: '取消',
    });
  }

  //删除文章
  const deleteArticle = async (ID) => {
    const data = await request.delete('v1/article/' + ID)
    console.log(data);
    getArticle()
    message.success('删除成功')
  }

  //查找分类下所有文章(只实现了拿选择的第一个分类的所有文章)
  const handleTableChange = (pagination, filters, sorter) => {
    let { cid } = filters
      //字符数组转整形数组
      let cidInt = []
      
      if(cid){
        if(CidList.toString()==cid.toString()){
          console.log(111);
          return 
        }
        cid.map(function (id) { cidInt.push(+id) })
      }
      setCidList([...cidInt])
  };
   //获取分类列表
   function getCategory() {
    axios.get(`/v1/category`).then(
      (res) => {
        console.log(res);
        let list = res.data.data.map((item)=>{
          return {text:item.name,value:item.id}
        })
        setCategoryList(list);
      },
      (err) => {
        console.log(err);
      }
    )
  }
  

  //表格数据配置
  const columns = [
    {
      title: 'ID',
      dataIndex: 'ID',
      key: 'ID'
    },
    {
      title: '分类',
      dataIndex: ['Category', 'name'],
      key: 'cid',
      filters: categoryList
    },
    {
      title: '文章标题',
      dataIndex: 'title',
      key: 'title',
    },
    {
      title: '管理',
      dataIndex: '',
      key: '',
      render: (record) => {
        return (
          <>
            <Button type="primary" className='margin_right' onClick={() => addArticle(record.ID)} >编辑</Button>
            <Button type="danger" onClick={() => confirm(record.ID)} >删除</Button>
          </>
        )
      }
    },

  ]

  return (
    <>
      <Card style={{}}>
        <Row gutter='20'>
          <Col span={6}>
            <Search placeholder="输入文章标题查找" onSearch={articleSearch} enterButton allowClear />
          </Col>
          <Col span={3}><Button type="primary" onClick={() => addArticle()}>添加文章</Button></Col>
        </Row>
        <Spin spinning={loading}>
        <Table pagination={paginationOption} columns={columns} dataSource={articleList} rowKey={i => i.ID} bordered onChange={handleTableChange} />
        </Spin>
      </Card>
    </>
  )
}
